package pers.qianyu.auth.controller;

import com.google.code.kaptcha.*;
import com.google.code.kaptcha.impl.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import org.springframework.security.core.context.*;
import org.springframework.security.web.authentication.*;
import org.springframework.web.bind.annotation.*;
import pers.qianyu.auth.pojo.dto.*;
import pers.qianyu.auth.pojo.entity.*;
import pers.qianyu.auth.security.model.*;
import pers.qianyu.auth.service.*;
import pers.qianyu.auth.utils.*;
import pers.qianyu.core.http.*;

import javax.imageio.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

@RestController
public class LoginController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;

    @PostMapping(value = "/login")
    public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest req) {
        // 从session中获取之前保存的验证码跟前台传来的验证码进行匹配
        Object kaptcha = req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (Objects.isNull(kaptcha)) {
            return HttpResult.error("验证码已失效");
        }
        if (!Objects.equals(loginBean.getCaptcha(), kaptcha)) {
            return HttpResult.error("验证码不正确");
        }
        // 用户信息
        UserPO userPO = userService.findByUsername(loginBean.getUsername());
        // 账号不存在、密码错误
        if (userPO == null) {
            return HttpResult.error("账号不存在");
        }
        // 账号锁定
        if (Objects.nonNull(userPO.getStatus()) && userPO.getStatus() == 0) {
            return HttpResult.error("账号已被锁定,请联系管理员");
        }
        // 系统登录认证
        JwtAuthenticationToken token = new JwtAuthenticationToken(loginBean.getUsername(), loginBean.getPassword());
        token.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
        // 执行登录认证过程
        Authentication authentication = authenticationManager.authenticate(token);
        // 认证成功存储认证信息到上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成令牌并返回给客户端
        token.setToken(JwtTokenUtils.generateToken(authentication));
        return HttpResult.ok(token);
    }

    /**
     * 生成验证码
     *
     * @param res 响应独享
     * @param req 请求对象
     * @throws IOException IO 异常
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse res, HttpServletRequest req) throws IOException {
        res.setHeader("Cache-Control", "no-store, no-cache");
        res.setContentType("image/jpeg");
        // 生成文字验证码
        String text = defaultKaptcha.createText();
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        // 保存到验证码到 session
        req.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = res.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.close();
    }
}